package executorService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.LongStream;

public class ExecutorServiceCalculator implements Calculator{

	private int parallism;
	
	private ExecutorService pool;
	
	public ExecutorServiceCalculator() {
		parallism = Runtime.getRuntime().availableProcessors();
		pool = Executors.newFixedThreadPool(parallism);
		
	}
	
	private static class SumTask implements Callable<Long>{
		private long[] numbers;
		private int from ;
		private int to;
	
		public SumTask(long[] numbers,int from,int to) {
			this.numbers = numbers;
			this.from = from ;
			this.to = to;
		}

		@Override
		public Long call() throws Exception {
			// TODO Auto-generated method stub
			long total = 0;
			for(int i=from ;i<= to;i++) {
				total += numbers[i];
			}
			return total;
		}
		
	}
	
	@Override
	public long sumUp(long[] numbers) {
		// TODO Auto-generated method stub
		List<Future<Long>> result = new ArrayList();
		
		int part = numbers.length / parallism;
		System.out.println("part=="+part);
		for(int i=0;i<parallism;i++) {
			int from  = i*part;
			int to = (i==parallism-1) ? numbers.length-1:(i+1)*part-1;
			System.out.println("from=="+from+"==to=="+to);
			
			result.add(pool.submit(new SumTask(numbers, from, to)));
		}
		long total = 0L;
		for(Future<Long> f : result) {
			try {
				total += f.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		pool.shutdown();
		return total;
	}
	
	public static void main(String[] args) {
		long[] numbers = LongStream.rangeClosed(1, 1000).toArray();
		ExecutorServiceCalculator esc = new ExecutorServiceCalculator();
		long total = esc.sumUp(numbers);
		System.out.println(total);
		
		int row = 33;
		int part = row/6;
		for(int i=0;i<6;i++) {
			int from = i*part;
			int to = (i==6-1) ? row-1 : (i+1)*part-1;
			System.out.println("from=="+from+"==to=="+to);
			for(int y=from;y<=to;y++) {
				//System.out.println("y=="+y);
			}
		}
	}
	

}
